<template>
  <view class="flex flex-col h-screen bg-[#f7f8fa]">
    <!-- 顶部导航栏 -->
    <nut-navbar :title="chatPartner.name || '聊天'" @on-click-back="goBack">
      <template #left>
        <nut-icon name="left"></nut-icon>
      </template>
    </nut-navbar>

    <!-- 消息列表区域 -->
    <scroll-view
      class="flex-1 overflow-y-auto p-2.5 pb-[60px] box-border scroll-view"
      :scroll-y="true"
      :scroll-into-view="`msg-${messages.length - 1}`"
      :scroll-with-animation="true"
    >
      <view v-for="(msg, index) in messages" :key="msg.conversationId" :id="`msg-${index}`">
        <view :class="['flex items-end mb-2.5', msg.isMe ? 'justify-end' : 'justify-start']">
          <nut-avatar v-if="!msg.isMe" size="small" :icon="chatPartner.avatar" />
          <view
            :class="[
              'px-3 py-2 rounded-[10px] max-w-[70%] text-sm leading-relaxed',
              msg.isMe ? 'bg-[#c9e9ff] ml-10 mr-1' : 'bg-white mr-10 ml-1',
            ]"
          >
            <text>{{ msg.content }}</text>
          </view>
          <nut-avatar v-if="msg.isMe" size="small" :icon="myAvatar" />
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view
      class="flex items-center p-2 bg-white border-t border-[#eee] fixed bottom-0 left-0 right-0 box-border z-[100]"
    >
      <nut-input
        v-model="newMessage"
        placeholder="请输入消息..."
        :border="false"
        class="flex-1 mr-2.5 bg-[#f7f8fa] rounded-[18px] px-3"
      />
      <nut-button type="primary" size="small" @click="sendMessage" :disabled="!newMessage.trim()">发送</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getMessage, customerSendMessage } from "@/api/message";

interface messages {
  conversationId: string;
  Content: string;
  isMe: string;
}

const chatPartner = ref({
  id: null as number | null,
  name: "加载中...",
  avatar: "https://img10.360buyimg.com/imagetools/jfs/t1/177407/37/27534/15689/61c3595aE07611298/3135d493e6c1199d.png",
  conversationId: "",
});

const myAvatar = ref(
  "https://img12.360buyimg.com/imagetools/jfs/t1/196430/38/8105/14329/60c806a4Ed506298a/e6de9fb7b8490f38.png"
);

const messages = ref<any>([]);
const newMessage = ref("");
let pollTimer: number | null = null;
const userType = ref(uni.getStorageSync("userType") || "customer");

onLoad((options) => {
  try {
    if (options && options.item) {
      const decodedItem = decodeURIComponent(options.item);
      const item = JSON.parse(decodedItem);
      chatPartner.value.id = item.contact_id;
      chatPartner.value.name = item.service_person_name;
      chatPartner.value.avatar = item.avatar;
      chatPartner.value.conversationId = item.conversation_id;
      fetchMessages(item.conversation_id);
      startPolling(item.conversation_id);
    } else {
      console.error("Chat page loaded without a personId!");
      uni.showToast({
        title: "无法加载聊天对象",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("解析聊天参数失败:", error);
    uni.showToast({
      title: "加载聊天失败",
      icon: "none",
    });
  }
});

onMounted(() => {
  scrollToBottom();
});

onUnmounted(() => {
  stopPolling();
});

const startPolling = (conversationId: string) => {
  stopPolling();
  pollTimer = setInterval(() => {
    fetchMessages(conversationId);
  }, 4000);
};

const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
};

//获取消息
const fetchMessages = async (conversationId: string) => {
  const userId = uni.getStorageSync("userId");
  const res: any = await getMessage(conversationId, userId);
  if (res.data) {
    // 根据用户类型处理消息的isMe属性
    messages.value = res.data.map((msg: any) => ({
      ...msg,
      isMe: userType.value === "customer" ? msg.senderId === userId : msg.senderId !== userId,
    }));
    scrollToBottom();
  }
};

//发送按钮
const sendMessage = async () => {
  const content = newMessage.value.trim();
  if (!content) return;

  const userId = uni.getStorageSync("userId");
  const newMsg = {
    content: content,
    receiverId: chatPartner.value.id,
    conversationId: chatPartner.value.conversationId,
    senderUserId: userId,
    senderId: userId,
    isMe: userType.value === "customer" ? true : false,
  };

  messages.value.push(newMsg);
  await customerSendMessage(newMsg);
  newMessage.value = "";
  scrollToBottom();
};

const goBack = () => {
  uni.navigateBack();
};
//跳到聊底部
const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query.select(".scroll-view").boundingClientRect();
    query.select(`#msg-${messages.value.length - 1}`).boundingClientRect();
    query.exec((res) => {
      if (res[1]) {
        uni.pageScrollTo({
          scrollTop: res[1].bottom,
          duration: 300,
        });
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.message-bubble {
  word-wrap: break-word;
  ::v-deep(.nut-input-control) {
    height: 36px;
    line-height: 36px;
  }
}
</style>
